<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>列宽自动分配 - 数据表格</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/layuiadmin/style/admin.css" media="all">
</head>
<body>

<div class="layui-card layadmin-header">
    <div class="layui-breadcrumb" lay-filter="breadcrumb">
        <a lay-href="">主页</a>
        <a><cite>组件</cite></a>
        <a><cite>数据表格</cite></a>
        <a><cite>列宽自动分配</cite></a>
    </div>
</div>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">列宽自动分配</div>
                <div class="layui-card-body">
                    <table id="demo" lay-filter="test"></table>
                </div>
            </div>
        </div>
    </div>
</div>
<form class="layui-form" action="" id="form" style="display:none;padding: 20px">
    <input type="hidden" id="id" name="id">
    <div class="layui-form-item">
        <label class="layui-form-label">用户名</label>
        <div class="layui-input-block">
            <input type="text" id="loginName" name="loginName" required  lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-block">
            <input type="password" id="password" name="password" required lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">备注</label>
        <div class="layui-input-block">
            <textarea name="remark" id="remark" placeholder="请输入备注" class="layui-textarea"></textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="formDemo">保存</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>
</body>
</html>
<script src="/layuiadmin/layui/layui.js"></script>
<!--行工具栏-->
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="delete">删除</button>
        <button class="layui-btn layui-btn-sm" lay-event="edit">编辑</button>
    </div>
</script>
<!--表头工具栏-->
<script type="text/html" id="toolbar">
    <div class="layui-btn-container">
        <button class="layui-btn" lay-event="add">添加</button>
        <button class="layui-btn layui-btn-danger " lay-event="deletes">删除选中</button>
    </div>
</script>
<script>
    layui.use(['table','form'], function () {
        var table = layui.table;
        var form = layui.form;
        var $ = layui.$
        //默认当前页和页面大小
        var currPage = 1
        var currPageSize = 10
        table.render({
            elem: '#demo',//表格的id值
            url: '/admin/list',
            toolbar: '#toolbar',
            request: {
                pageName: 'pageNo' //页码的参数名称，默认：page
                ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
            },
            parseData: function (res) { //res 即为原始返回的数据
                //重新赋值当前页和页面大小，后面重载当前页使用
                currPage = res.data.current
                currPageSize = res.data.size
                return {
                    "code": (0), //解析接口状态
                    "msg": "", //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records//解析数据列表
                };
            },
            cols: [
                [
                    {type: "checkbox", width: 100},
                    {field: 'id', title: 'ID'},
                    {field: 'loginName',  title: '用户名'},
                    {field: 'password', title: '密码'},
                    {field: 'lastLoginTime',  title: '上次登录'},
                    {field: 'remark',  title: '备注'},
                    {fixed: 'right', align:'center', toolbar: '#toolbarDemo'}
                ]
            ],
            limits: [10, 15, 20, 25, 50, 100],
            limit: 10,
            page: true,
            skin: 'line'
        });
        //toolbar为表头工具栏，test为lay-filter的值，而不是表格id值
        table.on('toolbar(test)', function(obj){
            var layEvent = obj.event;
            if (layEvent === 'add') {
                layer.open({
                    type: 1,
                    area: 'auto',
                    area: ['450px','360px'],
                    content: $('#form'),
                    cancel: function(index, layero){
                        //点击右上角关闭时，清空表单
                        $("#form")[0].reset()
                        layer.close(index)
                    }
                })
            }else if(layEvent === 'deletes'){
                var check_box =  table.checkStatus('demo').data;
                var ids = []
                $(check_box).each(function (index, item) {
                    ids.push(item.id)
                })
                if(ids.length === 0){
                    layer.msg("请至少选择一条数据",{icon: 5,time: 1000})
                }else {
                    layer.confirm("确认删除选中数据吗？删除后将无法恢复",{icon: 2,title: '提示'},function () {
                        $.ajax({
                            type: "post",
                            url: "/admin/deleteByIds",
                            data: {"ids": ids},
                            dataType: "json",
                            success: function (res) {
                                layer.msg("删除成功",{icno: 6,time:1000},function (id) {
                                    //刷新页面
                                    table.reload('demo', {
                                        url: '/admin/list'
                                        ,where: {
                                            "pageNo": currPage,
                                            "pageSize": currPageSize
                                        } //设定异步数据接口的额外参数
                                        //,height: 300
                                    });
                                })
                            }
                        })
                    },function (index) {
                        layer.close(index)
                    })

                }
            }
        });
        //tool为行工具栏
        table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

            if(layEvent === 'delete'){ //删除
                layer.confirm('真的确定删除该条数据吗？删除后将无法恢复',{icon: 0, title: '提示'}, function(index){
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    //向服务端发送删除指令
                    $.ajax({
                        type: "delete",
                        url: "/admin/"+data.id,
                        dataType: "json",
                        success: function (result) {
                            layer.close(index);
                            layer.msg("删除成功",{icno: 6,time:1000},function (id) {
                                //刷新页面
                                table.reload('demo', {
                                    url: '/admin/list'
                                    ,where: {
                                        "pageNo": currPage,
                                        "pageSize": currPageSize
                                    } //设定异步数据接口的额外参数
                                    //,height: 300
                                });
                            })
                        }
                    })
                });
            } else if(layEvent === 'edit'){ //编辑
                //打开弹框前，给弹框内容赋值
                $("#remark").val(data.remark)
                $("#loginName").val(data.loginName)
                $("#password").val(data.password)
                layer.open({
                    type: 1,
                    area: 'auto',
                    area: ['450px','360px'],
                    content: $('#form'),
                    cancel: function(index, layero){
                        //点击右上角关闭时，清空表单
                        $("#form")[0].reset()
                        layer.close(index)
                    }
                })
                //同步更新缓存对应的值
                obj.update({
                    username: '123'
                    ,title: 'xxx'
                });
            } else if(layEvent === 'LAYTABLE_TIPS'){
                layer.alert('Hi，头部工具栏扩展的右侧图标。');
            }
        });

        //复选框
        table.on('checkbox(test)', function(obj){
            console.log(obj.checked); //当前是否选中状态
            console.log(obj.data); //选中行的相关数据
            console.log(obj.type); //如果触发的是全选，则为：all，如果触发的是单选，则为：one
            //获取所有被选中行
            var check_box =  table.checkStatus('demo').data;
            console.info(check_box)
        });

        //表单绑定事件
        form.on('submit(formDemo)', function(data){
            console.log(data.field);//当前容器的全部表单字段，名值对形式：{name: value}
            $.ajax({
                type: "post",
                url: "/admin/",
                data: data.field,
                dataType: "json",
                success: function (res) {
                    layer.msg("保存成功",{icno: 6,time:1000},function (id) {
                        //关闭弹框
                        layer.closeAll()
                        //清空表单值
                        $("#form")[0].reset()
                        //刷新页面
                        table.reload('demo', {
                            url: '/admin/list'
                            ,where: {
                                "pageNo": currPage,
                                "pageSize": currPageSize
                            } //设定异步数据接口的额外参数
                            //,height: 300
                        });
                    })
                }
            })
            return false
        });
    });
</script>